import Vue from 'vue';
import VueRouter from 'vue-router';
import routes, { Route } from './routes';
Vue.use(VueRouter);

const getMappedRoutes = (r: Array<Route>): Array<Route> => (
  r.map(route => ({
    ...route,
    // 按需加载
    component: () => import(`@/views/${route.page}.vue`),
    children: route.children ? getMappedRoutes(route.children) : undefined,
  }))
);

const router = new VueRouter({
  mode: 'hash',
  routes: getMappedRoutes(routes),
});

router.beforeEach((to, from, next) => {
  let title = to.name || 'Home';
  document.title = title;
  // 拦截
  next();
})

export default router;